<template>
    <div class="weekly-summary-container">
        <!-- 周选择器（仅当没有content时显示） -->
        <el-form v-if="!props.content" :inline="true" class="search-form">
            <el-form-item label="选择周次">
                <el-date-picker v-model="selectedDate" type="week" format="YYYY年 第ww周" value-format="YYYY-ww"
                    placeholder="选择周次" @change="fetchSummary" />
            </el-form-item>
        </el-form>

        <AIWarningTips v-if="showAITips" />
        <!-- 内容显示区 -->
        <div class="content-area">
            <div v-if="formattedContent" class="markdown-container markdown-body" v-html="renderedContent" />
            <el-empty v-else image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
import { ElMessage } from 'element-plus'
import MarkdownIt from 'markdown-it'
import mermaid from 'mermaid'
import { computed, onMounted, ref, watch } from 'vue'
import { asyncGetActivityUserWeeklySummary } from '../../api'
import AIWarningTips from '../AIWarningTips.vue'

// 初始化dayjs插件
dayjs.extend(isoWeek)

const props = defineProps({
    userid: { type: Number, default: undefined },
    date: { type: String, default: '' },
    content: { type: String, default: undefined },
    showAITips: { type: Boolean, default: true }
})

const selectedDate = ref(props.date || dayjs().format('YYYY-ww'))
const internalContent = ref('')

const formattedContent = computed(() => props.content ?? internalContent.value)
const renderedContent = computed(() => renderMarkdown(formattedContent.value))

onMounted(() => {
    if (!props.content && validateProps()) {
        fetchSummary()
    }
})

watch(() => props.date, (newVal) => {
    if (newVal && newVal !== selectedDate.value) {
        selectedDate.value = newVal
    }
})

function validateProps() {
    if (!props.content && (!props.userid || !selectedDate.value)) {
        ElMessage.warning('必须提供用户ID和日期（当未提供content时）')
        return false
    }
    return true
}

async function fetchSummary() {
    if (!validateProps()) return

    try {
        const [year, week] = selectedDate.value.split('-').map(Number)
        const { rows } = await asyncGetActivityUserWeeklySummary({
            userid: [props.userid!],
            year,
            week
        })

        internalContent.value = rows[0]?.content || ''
    } catch (error) {
        console.error('获取周总结失败:', error)
        ElMessage.error('获取数据失败')
    }
}

function renderMarkdown(content: string) {
    if (!content) return ''
    const html = new MarkdownIt().render(content)
    mermaid.init({ startOnLoad: false }, '.mermaid')
    return html
}
</script>

<style scoped>
.weekly-summary-container {
    margin-top: -20px;
    /* display: flex;
    flex-direction: column; */
}

.search-form {
    margin-bottom: 12px;
}

.content-area {
    min-height: 200px;
}

.markdown-container {
    padding: 16px;
    background-color: var(--el-bg-color);
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color);
    overflow: auto;
}
</style>